#!/usr/bin/python
# -*- coding: utf-8 -*-
import sys
try: print "encoding: "+sys.getdefaultencoding()
except:	pass
try: sys.setdefaultencoding('iso-8859-1')
except:	pass

import urllib,urllib2,re,imp,os
import xbmcplugin,xbmcgui,xbmc
import iload,debugcode

#path=xbmc.translatePath('Q:\\plugins\\hoster\\oracle\\interface2.py')
path=xbmc.translatePath(os.path.join(os.path.normpath(os.path.join(os.getcwd(),os.pardir,os.pardir)),'hoster'+os.sep+'oracle'+os.sep+'interface2.py'))
interface2=imp.load_source("interface2", "interface2.py", open(path,'r'))


#author:
#elypter
#-mail:elypter@yahoo.de
#
#thanks to: Voinage, who made this great tutorial http://xbmc.org/wiki/?title=HOW-TO_write_plugins_for_XBMC
#			the xbmc developers
#			iload.to for providing the great platform and content-database

debug=1
dstr="##*iload*default*"
if debug > 0: print dstr+" debug: "+ str(debug)

baseurl="http://iload.to/de"
jd_url="http://localhost:8765"	#If you want to be able to download with jdownloader on a pc, 
								#enable the webinterface of jd ,disable password and modifie the jd_url value
								#to something like this http://ip:port

def CATEGORIES():
	#the plugin executes this first (start is @ [entry point])
	
	addDir('Debug','0',1,'')
	addDir('Filme','||',2,'')
	addDir('Filme(dbg)','2',1,'')
	addDir('Dokus','334||',2,'')
	addDir('Serien(dbg)','6',1,'')
		
def DEBUG(param):
	debugcode.DEBUG(param)

def MOVIES(param):
	#handles movie-category-list, dokus, movie-list, searches (movies, dokus, shows), sorting, page-list
	
	category,sort,page = param.split('|')
	#category: content-category(the number in front of the category name in the iload-url)
	#sort: search string(with '-' in front of) or sorting-string in the form of x-x eg 3-1 ->watch the url
	#page: select wich page should be displayed
	if page=='':
		if category == '':
			#list movie-categories
			
			#layout wurde geaendert
			#cat=iload.get_categories()
			#i=0
			#for url,size,name,sub in cat:
			#	if url =='1':
			#		u=0
			#		addDir("_Alle", '1'+'|'+'|', 2, '')
			#		for url,size,name in sub:
			#			addDir(name, url+'|'+'|', 2, '')
			#			u=u+1
			#	i=i+1
			
			mov=iload.get_mcat()
			u=0
			addDir("_Alle", '1'+'|'+'|', 2, '')
			for url,size,name in mov:
				addDir(name, url+'|'+'|', 2, '')
				if debug > 0: print dstr+"MOVIES* addDir('"+name+"','"+url+"||',2,'')"
				u=u+1
			
		else:
			if sort=='':
				#list sorting methods and search-option
				addDir("_Suche", category+'|'+'-'+'|', 2, '')
				addDir("Datum, absteigend", category+'|'+'0-0'+'|', 2, '')
				addDir("Datum, aufsteigend", category+'|'+'0-1'+'|', 2, '')
				addDir("Name, absteigend", category+'|'+'1-1'+'|', 2, '')
				addDir("Name, aufsteigend", category+'|'+'1-0'+'|', 2, '')
				addDir("Hits, absteigend", category+'|'+'2-0'+'|', 2, '')
				addDir("Hits, aufsteigend", category+'|'+'2-1'+'|', 2, '')
				addDir("Downloads, absteigend", category+'|'+'3-0'+'|', 2, '')
				addDir("Downloads, aufsteigend", category+'|'+'3-1'+'|', 2, '')
				addDir("Bewertung, absteigend", category+'|'+'4-0'+'|', 2, '')
				addDir("Bewertung, aufsteigend", category+'|'+'4-1'+'|', 2, '')
			else:
				#list search results (either by asking or by given argument)
				if sort == "-":
					#prompt search dialog
					kb = xbmc.Keyboard('default', 'heading', False)
					kb.setDefault('') # optional
					kb.setHeading('Enter search') # optional
					kb.doModal()
					if (kb.isConfirmed()):
						sort = "-"+kb.getText()
				n=iload.set_sort(category,sort)
				i=0
				if n >1:
					addDir('_Alle Seiten', category+'|'+sort+'|'+'0', 2, '')
					while i<n:
						i=i+1
						addDir('Seite '+str(i), category+'|'+sort+'|'+str(i), 2, '')
				else:
					MOVIES(category+'|'+sort+'|'+str(1))
	elif page=='0':
		#combine all pages (list content)
		n=iload.set_sort(category,sort)
		u=0
		while u<n:
			u=u+1
			i=0
			for id,img,name in iload.get_movies(category,u,sort):
				i=i+1
				if img == "/img/no_thumb.gif":
					img = baseurl+"/img/no_thumb.gif"
				addDir(str(u*30+i)+". "+name, baseurl+"/title/"+id+"/", 3, img)
	else:
		#view specified page (list content)
		i=0
		for id,img,name in iload.get_movies(category,page,sort):
			i=i+1
			if img == "/img/no_thumb.gif":
				img = baseurl+"/img/no_thumb.gif"
			addDir(str(i)+". "+name, baseurl+"/title/"+id+"/", 3, img)

def TITLE(url):
	#list all available releases of a title (movie, doku or episode)
	i=0
	r=iload.get_releases(url)
	
	if len(r)>1:
		for release in r:
			i=i+1
			#id,name = release.split('-')
			addDir(release, baseurl+"/release/"+release, 4, '')
			#addDir("release "+str(i)+" ("+release+")", baseurl+"/release/"+release+"/ReleaseTab/Streams/", 4, '')
	else:
		RELEASE(baseurl+"/release/"+r[0]+"/ReleaseTab/Streams/")
			
			
def RELEASE(release):
	#display all hoster-links and display captchas if needed
	
	#match,downloads=iload.get_mirrors(release)

	#link for remote-downloading with jdownloader
	#if len(downloads)>0:
	#	addLink("_Lade mit jdownloader an "+jd_url, jd_url+"/link_adder.tmpl?do=Add&do=Add&addlinks="+urllib.quote(str(downloads)),"http://jdownloader.org/_media/knowledge/wiki/jdownloader.png?w=100&h=100")
	
	#oracleurls=[]
	#for img,name,content in match:
	#	for sid,lid,file in content:
						
	#		addDir(name+" ("+file+")", baseurl+"/go/"+sid+"/streaming/"+lid, 7, img)
			#oracleurls.append((("get_links_by_source",(iload.resolve(baseurl+"/go/"+sid+"/streaming/"+lid),[]),(img,name,"","hoster noch unbekannt"))))		
	

	for id,host,sid,file in iload.get_mirrors(release):
		#oracleurls=get_links_by_source(iload.resolve(baseurl+"/de/go/"+id+"-"+host+"/file/"+sid+"-"+file+"/"),[])
			addDir(host+" ("+file+")", baseurl+"/de/go/"+id+"-"+host+"/file/"+sid+"-"+file+"/", 7, '')
			#interface2.ACTION_LIST(str(iload.resolve(baseurl+"/de/go/"+id+"-"+host+"/file/"+sid+"-"+file+"/")),host,file)
				#MIRROR(baseurl+"/de/go/"+id+"-"+host+"/file/"+sid+"-"+file+"/",host,file)
		#interface2.addLink("Play "+host+" ("+file+")", oracle2.str(iload.resolve(baseurl+"/de/go/"+id+"-"+host+"/file/"+sid+"-"+file+"/")), "")

		
def MIRROR(url,file):
	oracleurls=[]
	oracleurls.append((("get_links_by_source",(iload.resolve(url),[]),('noimg','notitle',file,'nohost'))))
	interface2.MIRROR_LIST(oracleurls)
	
	


def SHOWS(param):
	#handles show-list, seasonlist, episode-list
	category,episode = param.split('|')
	if episode =='':
		if category=='':
			#list shows
			
			#layout wurde geaendert
			#cat=iload.get_categories()
			#i=0
			#for url,size,name,sub in cat:
			#	if url =='6':
			#		u=0
			#		addDir("._Suche", str(6)+'|'+'-'+'|', 2, '')
			#		for url,size,name in sub:
			#			addDir(name, url+'|', 6, '')
			#			u=u+1
			#	i=i+1
			
			ser=iload.get_scat()
			u=0
			addDir("._Suche", str(6)+'|'+'-'+'|', 2, '')
			for url,size,name in ser:
				addDir(name, url+'|', 6, '')
				if debug > 0: print dstr+"SHOWS* addDir('"+name+"', '"+url+"'+'|', 6, '')"
				u=u+1
		else:
			#list seasons
			addDir("._Suche", category+'|'+'-'+'|', 2, '')
			for url,name in iload.get_simple_list(baseurl+"/category/"+category+"/"):
				addDir(name, category+"|"+baseurl+url, 6, '')
	else:
		#list episodes
		for url,name in iload.get_episodes(episode):
			addDir(name, baseurl+"/title/"+url, 3, '')
		
	


				
def get_params():
		param=[]
		paramstring=sys.argv[2]
		if len(paramstring)>=2:
				params=sys.argv[2]
				cleanedparams=params.replace('?','')
				if (params[len(params)-1]=='/'):
						params=params[0:len(params)-2]
				pairsofparams=cleanedparams.split('&')
				param={}
				for i in range(len(pairsofparams)):
						splitparams={}
						splitparams=pairsofparams[i].split('=')
						if (len(splitparams))==2:
								param[splitparams[0]]=splitparams[1]
								
		return param




def addLink(name,url,iconimage):
		ok=True
		liz=xbmcgui.ListItem(name, iconImage="DefaultVideo.png", thumbnailImage=iconimage)
		liz.setInfo( type="Video", infoLabels={ "Title": name } )
		ok=xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]),url=url,listitem=liz)
		return ok


def addDir(name,url,mode,iconimage):
		u=sys.argv[0]+"?url="+urllib.quote_plus(url)+"&mode="+str(mode)+"&name="+urllib.quote_plus(name)
		ok=True
		liz=xbmcgui.ListItem(name, iconImage="DefaultFolder.png", thumbnailImage=iconimage)
		liz.setInfo( type="Video", infoLabels={ "Title": name} )
		ok=xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]),url=u,listitem=liz,isFolder=True)
		return ok
		

#[entry point]		
params=get_params()
url=None
name=None
mode=None

try:
		url=urllib.unquote_plus(params["url"])
except:
		pass
try:
		name=urllib.unquote_plus(params["name"])
except:
		pass
try:
		mode=int(params["mode"])
except:
		pass

if debug > 0: print dstr+" Mode: "+str(mode)
if debug > 0: print dstr+" URL: "+str(url)
if debug > 0: print dstr+" Name: "+str(name)

#finding out wich method should be launched
if mode==None or url==None or len(url)<1:
	print ""
	CATEGORIES()

elif mode == 1:
	print ""+url
	DEBUG(url)
	
elif mode == 2:
	print ""+url
	MOVIES(url)

elif mode == 3:
	print ""+url
	TITLE(url)
	
elif mode == 4:
	print ""+url
	RELEASE(url)

elif mode == 5:
	print ""+url
	VERIFY(url)

elif mode == 6:
	print ""+url
	SHOWS(url)
	
elif mode == 7:
	print ""+url+""+name
	MIRROR(url,name)

	
#xbmcplugin.addSortMethod( handle=int(sys.argv[1]), sortMethod=xbmcplugin.SORT_METHOD_NONE )
xbmcplugin.endOfDirectory(int(sys.argv[1]))
